//
//  DaodeManager.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/7.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import AMapFoundationKit
import MAMapKit
import AMapSearchKit
import AMapLocationKit

class GaodeManager: NSObject {
    
    var gaodeProtocol: GaodeProtocol!
    
    static var locationManager = AMapLocationManager()
    public func getLocationInfo() {
        
        GaodeManager.locationManager.desiredAccuracy = kCLLocationAccuracyBest

        GaodeManager.locationManager.locationTimeout = 10

        GaodeManager.locationManager.reGeocodeTimeout = 10
        
        GaodeManager.locationManager.requestLocation(withReGeocode: true, completionBlock: { (location: CLLocation?, reGeocode: AMapLocationReGeocode?, error: Error?) in
            
            if let error = error {
                let error = error as NSError
                
                if error.code == AMapLocationErrorCode.locateFailed.rawValue {
                    //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
                    NSLog("定位错误:{\(error.code) - \(error.localizedDescription)};")
                    return
                }
                else if error.code == AMapLocationErrorCode.reGeocodeFailed.rawValue
                    || error.code == AMapLocationErrorCode.timeOut.rawValue
                    || error.code == AMapLocationErrorCode.cannotFindHost.rawValue
                    || error.code == AMapLocationErrorCode.badURL.rawValue
                    || error.code == AMapLocationErrorCode.notConnectedToInternet.rawValue
                    || error.code == AMapLocationErrorCode.cannotConnectToHost.rawValue {
                    
                    //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
                    NSLog("逆地理错误:{\(error.code) - \(error.localizedDescription)};")
                }
                else {
                    //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
                }
            }
            
            if let location = location {
                NSLog("location:%@", location)
            }
            
            if let reGeocode = reGeocode {
                NSLog("reGeocode:%@", reGeocode)
            }
        })
    }

    class public func creatMapContent() -> MAMapView {
        let mapView: MAMapView = MAMapView()
        AMapServices.shared().enableHTTPS = true
//        mapView.delegate = self.currentVC as? MAMapViewDelegate
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        return mapView
    }
    
    class public func currentPoint(mapView: MAMapView) {
        let r = MAUserLocationRepresentation()
        r.showsAccuracyRing = false//精度圈是否显示
        r.showsHeadingIndicator = true//是否显示蓝点方向指向
        r.fillColor = UIColor.red//调整精度圈填充颜色
        r.strokeColor = UIColor.blue//调整精度圈边线颜色
        r.lineWidth = 2//调整精度圈边线宽度
        r.enablePulseAnnimation = false//精度圈是否显示律动效果
        r.locationDotBgColor = UIColor.green//调整定位蓝点的背景颜色
        r.locationDotFillColor = UIColor.gray// 调整定位蓝点的颜色
        r.image = UIImage(named: "您的图片")//调整定位蓝点的图标
        mapView.update(r)
    }
    
    class public func mapSearch() {
        let search: AMapSearchAPI = AMapSearchAPI()
//        search.delegate =  self.currentVC as? AMapSearchDelegate
        
//        let request = AMapPOIKeywordsSearchRequest()
//        request.keywords = keyword
//        request.requireExtension = true
//        request.city = "北京"
//
//        request.cityLimit = true
//        request.requireSubPOIs = true
//        search.aMapPOIKeywordsSearch(request)
        
        
        let request = AMapPOIAroundSearchRequest()
//        request.tableID = tingchechangTableID
                //32.015136,118.887949
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(32.015136), longitude: CGFloat(118.887949))
        request.keywords = "停车场"
        request.requireExtension = true
        
        search.aMapPOIAroundSearch(request)
    }
    
//    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
//        
//        print(response)
//        if response.count == 0 {
//            return
//        }
//        
//        //解析response获取POI信息，具体解析见 Demo
//    }

    // 线路规划
    class public func routePlanning(_ body: [String: Any]) {
        // 纬度 Latitude  经度 Longitude  南京北纬32 东经119
        let startLatStr: String = body["startLat"]! as! String
        let startLonStr: String = body["startLon"]! as! String
        let startLat: Double = Double(startLatStr)!
        let startLon: Double = Double(startLonStr)!
        
        let endLatStr: String = body["endLat"]! as! String
        let endLonStr: String = body["endLon"]! as! String
        let endLat: Double = Double(endLatStr)!
        let endLon: Double = Double(endLonStr)!
        
        let startAddressStr: String = body["startAddress"]! as! String
        let endAddressStr: String = body["endAddress"]! as! String
        
        let urlString: String = String(format: "iosamap://path?sourceApplication=applicationName&sid=&slat=%.6f&slon=%.6f&sname=%@&did=&dlat=%.6f&dlon=%.6f&dname=%@&dev=0&t=0", startLat, startLon, startAddressStr, endLat, endLon, endAddressStr)
        
        // swift 必须要有这个
        let urlSSSS = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let url = URL(string: urlSSSS!)
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
        } else {
            
        }
    }
    
    
}
